import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, parseToken, getUserFromToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    status: '',
    userId: '',
    email: '',
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_STATUS: (state, status) => {
    state.status = status
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_EMAIL: (state, email) => {
    state.email = email
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        
        // 检查JWT token
        let token = '';
        
        if (data.data && data.data.token) {
          token = data.data.token;
          
          // 解析JWT获取用户基本信息
          const decodedToken = parseToken(token);
          console.log('JWT解析结果:', decodedToken);
          
          if (decodedToken) {
            // 如果JWT包含用户信息，直接保存
            if (decodedToken.sub) commit('SET_USER_ID', decodedToken.sub);
            if (decodedToken.username) commit('SET_NAME', decodedToken.username);
            if (decodedToken.email) commit('SET_EMAIL', decodedToken.email);
            
            // 处理角色信息
            const roles = decodedToken.roles || decodedToken.authorities || [];
            if (roles.length) commit('SET_ROLES', Array.isArray(roles) ? roles : [roles]);
          }
        } else {
          // 如果后端没有返回有效JWT，使用临时token
          token = 'temp_token_' + username + '_' + new Date().getTime();
          console.log('后端未返回JWT token，使用临时token:', token);
        }
        
        // 保存token
        commit('SET_TOKEN', token);
        setToken(token);
        
        // 保存用户名到localStorage用于应急措施
        localStorage.setItem('username', username);
        
        resolve(data);
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 首先尝试从JWT中获取用户信息
      const userFromToken = getUserFromToken();
      
      if (userFromToken) {
        console.log('从JWT中获取到用户信息:', userFromToken);
        
        // 设置用户基本信息
        const username = userFromToken.username || localStorage.getItem('username') || 'Guest';
        commit('SET_NAME', username);
        commit('SET_STATUS', userFromToken.status || 1);
        commit('SET_AVATAR', userFromToken.avatar || '');
        
        if (userFromToken.sub) commit('SET_USER_ID', userFromToken.sub);
        if (userFromToken.email) commit('SET_EMAIL', userFromToken.email);
        
        // 处理角色信息
        const roles = userFromToken.roles || userFromToken.authorities || [];
        if (roles.length) commit('SET_ROLES', Array.isArray(roles) ? roles : [roles]);
        
        resolve(userFromToken);
        return;
      }
      
      // 如果JWT中没有足够信息，再调用API
      getInfo(state.token).then(response => {
        console.log('获取用户信息响应:', response);

        const { data } = response;
        
        // 如果服务器返回了错误状态码，但我们想继续执行
        if (response.status >= 400) {
          console.warn('服务器返回错误状态码:', response.status);
          
          // 创建默认用户信息替代
          const mockUserInfo = {
            username: localStorage.getItem('username') || 'Guest User',
            avatar: '',
            status: 1
          };
          
          // 保存模拟的用户信息
          commit('SET_NAME', mockUserInfo.username);
          commit('SET_AVATAR', mockUserInfo.avatar);
          commit('SET_STATUS', mockUserInfo.status);
          
          return resolve(mockUserInfo); // 返回模拟数据
        }
        
        if (!data) {
          return reject('验证失败请重新登录.');
        }

        // 提取用户信息，处理可能缺失的字段
        let username = data.username || localStorage.getItem('username') || 'unknown';
        let avatar = data.avatar || '';
        let status = data.status;
        let email = data.email || '';
        let userId = data.id || '';
        
        // 确保status为数字类型
        status = typeof status === 'number' ? status : 1;
        
        // 保存用户信息
        commit('SET_NAME', username);
        commit('SET_AVATAR', avatar);
        commit('SET_STATUS', status);
        if (email) commit('SET_EMAIL', email);
        if (userId) commit('SET_USER_ID', userId);
        
        // 处理角色信息
        if (data.roles) {
          const roles = Array.isArray(data.roles) ? data.roles : [data.roles];
          commit('SET_ROLES', roles);
        }
        
        resolve(data);
      }).catch(error => {
        console.error('获取用户信息失败:', error);
        
        // 创建默认用户信息替代
        const mockUserInfo = {
          username: localStorage.getItem('username') || 'Guest User',
          avatar: '',
          status: 1
        };
        
        // 保存模拟的用户信息
        commit('SET_NAME', mockUserInfo.username);
        commit('SET_AVATAR', mockUserInfo.avatar);
        commit('SET_STATUS', mockUserInfo.status);
        
        // 如果我们不想拒绝Promise，可以解析而不是拒绝
        resolve(mockUserInfo); // 不会触发路由守卫中的catch块
      });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove token first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        console.error('注销失败，但仍清除本地状态:', error);
        removeToken() // 无论如何都删除token
        resetRouter()
        commit('RESET_STATE')
        resolve() // 仍然解析Promise
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove token first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

